//
//  BlockedViewController.m
//  jungoo
//
//  Created by Dang Quang Trung on 7/25/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "BlockedViewController.h"
#import "Extensions.h"
#import <QuartzCore/QuartzCore.h>
#import "JGoAPI.h"
#import "Utility.h"
@implementation BlockedViewController

@synthesize blockedPeople = dataSource;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - Private Method

- (void)applyAppearance
{
    [self setRightButtonImageActiveName:nil 
                           inactiveName:@"edit-button"
                                 target:self 
                                 action:@selector(editPressed)];
    [self setBackButtonImageActiveName:nil 
                           inactiveName:@"back-button"
                                 target:self 
                                 action:@selector(backPressed)];   
    [self setTitle:@"Blocked"];
    
    [self.tableView setAllowsSelectionDuringEditing:NO];
}

- (void)asyncLoadAvatar
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
    
    dispatch_async(queue, ^{
        
        for (NSDictionary *aPerson in dataSource) {
            NSError *error = nil;
            UIImage * personAvatar = [JGoAPI downloadAvatar:[aPerson objectForKey:@"thumb"] error:&error];
            
            if (error == nil) {
                [aPerson setValue:personAvatar forKey:@"avatar"];
                [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
            }
            else {
                [aPerson setValue:[UIImage imageNamed:@"photo-frame"] forKey:@"avatar"];
            }
        }    
    });
}
                   
- (UITableViewCell*)myCell
{
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"BlockedCell" owner:nil options:nil];
    
    return [views objectAtIndex:0];
}

- (UITableViewCell*)editCell
{
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"BlockedCell" owner:nil options:nil];
    
    return [views objectAtIndex:1];
}

#pragma mark - View lifecycle

-(void) backPressed 
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void) editPressed 
{
    [self.tableView setEditing:!self.tableView.editing];
    
    if (self.tableView.editing) {
        [self setRightButtonImageActiveName:nil 
                               inactiveName:@"done-button"
                                     target:self 
                                     action:@selector(editPressed)];        
    }
    else {
        [self setRightButtonImageActiveName:nil 
                               inactiveName:@"edit-button"
                                     target:self 
                                     action:@selector(editPressed)];        
    }
    
    [self.tableView reloadData];
}

- (void)viewDidLoad
{    
    NSLog(@"%@",dataSource);
    [super viewDidLoad];
    
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.opaque = NO;
    self.tableView.backgroundView = nil;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.allowsSelection = YES; 
    
    [self asyncLoadAvatar];
}

-(void)viewWillAppear:(BOOL)animated
{
    [self applyAppearance];
    [super viewWillAppear:animated];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return NO;
}
-(void)dealloc
{
    [self setTableView:nil];
    [super dealloc];
}

#pragma mark - Table Delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 46;
    }
    
    return 72;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return dataSource ? [dataSource count] + 1 : 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;    
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{            
    UITableViewCell *cell  = nil;
    
    if (indexPath.section > 0) {

        NSDictionary *aBlocked = [dataSource objectAtIndex:indexPath.section - 1];

        if (!tableView.editing) {
            cell = [self myCell];
        }
        else {
            cell = [self editCell];
        }    

        UIImage *avatar = [aBlocked objectForKey:@"avatar"];
        NSDate *dob = [JGoUtility dateFromString1:[aBlocked objectForKey:@"dob"]];
        NSString *dobString = [JGoUtility stringFromDate4:dob];
        
        cell.backgroundColor = [UIColor clearColor];        
        cell.selectionStyle = UITableViewCellSelectionStyleGray;

        [cell titleTextWithTag:2].text = [aBlocked objectForKey:@"name"];
        [cell titleTextWithTag:3].text = dobString;
        [cell titleTextWithTag:4].text = [aBlocked objectForKey:@"university"];
        [cell imageViewWithTag:1].image = avatar ? avatar : [UIImage imageNamed:@"photo-frame"];
        
        [cell imageViewWithTag:1].layer.borderColor = [[UIColor whiteColor] CGColor];
        [cell imageViewWithTag:1].layer.borderWidth = 2;
        [cell imageViewWithTag:1].layer.shadowColor = [[UIColor blackColor] CGColor];
        [cell imageViewWithTag:1].layer.shadowRadius = 1;
        [cell imageViewWithTag:1].layer.shadowOpacity = 0.45;
        [cell imageViewWithTag:1].layer.shadowOffset = CGSizeMake(0, 0);
    }
    else {
        cell = cellTop;
        
        if (!tableView.editing) {
            cell.userInteractionEnabled = YES;
        }
        else {
            cell.userInteractionEnabled = NO;
        }    
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0: {
            
            break;             
        }
        case 2: {                                      
        }

        default:
            break;
    }    
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return NO;
    }
    
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
		NSDictionary *person = [dataSource objectAtIndex:indexPath.section - 1];
        blockedUser = person;
        [JGoUtility showProgressInView:self.view
                                target:self 
                                 title:@"Unblocking..." 
                              selector:@selector(delayUnblock:)];

		
    }   
}

- (void)delayUnblock:(MBProgressHUD*)progress
{
    NSString *userId = [[JGoUtility sharedCreateAccount] objectForKey:@"user_id"];
    NSError *error = nil;
    
    [JGoAPI unblockPersonWithUserID:userId UnblockedUser:[blockedUser objectForKey:@"user_id"] error:&error];    
    if (error) {
        [JGoUtility showAlert:[error localizedDescription]];
    }
    [dataSource removeObject:blockedUser];
    [self.tableView reloadData];
    [progress hide:YES];
}
- (void)delayBlock:(MBProgressHUD*)progress
{
    NSString *userId = [[JGoUtility sharedCreateAccount] objectForKey:@"user_id"];
    NSError *error = nil;
    
    [JGoAPI blockPersonWithUserID:userId blockedUser:[blockedUser objectForKey:@"user_id"] error:&error];

    
    if (error) {
        [JGoUtility showAlert:[error localizedDescription]];
    }
    [dataSource addObject:blockedUser];
    [self.tableView reloadData];
    [progress hide:YES];
}
-(IBAction)addPeople:(id)sender
{
    PeopleViewController *pVC = [[PeopleViewController alloc]initWithNibName:@"PeopleViewController" bundle:nil];
    pVC.delegate = self;
    pVC.peopleView = BlockMode;
    [self.navigationController pushViewController:pVC animated:YES];
    
    [pVC release];
}
- (void)didSelectedPerson:(NSDictionary*)userinfo {
    NSLog(@"%@",userinfo);
    blockedUser = userinfo;
    [JGoUtility showProgressInView:self.view
                            target:self 
                             title:@"Blocking..." 
                          selector:@selector(delayBlock:)];
    
    
}
@end
